from rest_framework.validators import UniqueTogetherValidator

from guides.models import *
from rest_framework import serializers


# Create your serializers here.

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField(initial='lele@qq.com')
    content = serializers.CharField(max_length=20)
    created = serializers.DateTimeField()

    def create(self, validated_data):
        return Comment.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.content = validated_data.get('content', instance.content)
        instance.created = validated_data.get('created', instance.created)
        instance.save()
        return instance

    def validate_content(self, value):
        # 字段级别的验证
        if "wenliang" not in value.lower():
            raise serializers.ValidationError("要爱阿凉哦")
        return value



class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = '__all__'

    def validate(self, data):
        # 对象级别的验证，data是一个字典
        if data['start'] > data['finish']:
            raise serializers.ValidationError("finish must occur after start")
        return data


class Event1Serializer(serializers.ModelSerializer):
    GEEKS_CHOICES = (
        ("1", "One"),
        ("2", "Two"),
        ("3", "Three"),
        ("4", "Four"),
        ("5", "Five"),
    )
    # name = serializers.MultipleChoiceField(choices=GEEKS_CHOICES)  #模型类里要是字符串
    name =serializers.CharField(min_length=3)
    # room_number = serializers.IntegerField(validators=[multiple_of_ten])
    # choices = [100, 101, 103, 105]

    room_number = serializers.IntegerField()
    date = serializers.DateField()

    class Meta:
        model = Event1
        fields = ['id', 'name','room_number','date']
        # validators必须是列表类型
        validators = [
            UniqueTogetherValidator(
                queryset=Event1.objects.all(),
                fields=['room_number', 'date']
            )
        ]

class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user


#序列化关系
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
    #StringRelatedField显示效果是 对象自身打印出来的样子，也就是str方法
    #tracks的名字必须和模型类中的related_name名字一致
    # tracks = serializers.StringRelatedField(many=True)
    # tracks = serializers.PrimaryKeyRelatedField(many=True,read_only=True) #用的不多
    tracks=serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='track-detail'
    )
    class Meta:
        model=Album
        fields = ['url','album_name', 'artist', 'tracks']


class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model=Track
        fields = '__all__'